<?php

namespace app\common\controller;

use app\BaseController;
use app\common\traits\JumpTrait;
use app\admin\model\IndexUser as User;
use think\facade\Cache;
use think\facade\Session;
use think\facade\View;
use UserHub\Client;

class AuthController extends BaseController
{

    use JumpTrait;

    public $modelUser = null;

    public $disableLogin = false;

    public function initialize()
    {

        parent::initialize();

        if ($this->verifyAuthRequire()) {
            $code = $this->request->param('code');

            $user_hub_client = new Client([
                'key' => sysconfig('user_hub', 'user_hub_key'),
                'secret' => sysconfig('user_hub', 'user_hub_secret'),
                'host' => sysconfig('user_hub', 'user_hub_host'),
            ]);
            if (empty($code)) {
                $url = $user_hub_client->getBowserRedirectUrl($this->request->url(true));
                return $this->error('请登录', null, $url);
            } else {
                $user_info = $user_hub_client->getUserinfoByCode($code);

                $model_user = User::where('uid', $user_info['uid'])->find();
                $user_uid = $user_info['uid'];
                if (empty($model_user)) {
                    unset($user_info['id']);
                    // TODO:处理数据,或者中转数据
                    // TODO:下载头像

                    $model_user = User::create((array)$user_info);
                }

                if ($model_user->nickname != $user_info['nickname']) {
                    $model_user->nickname = $user_info['nickname'];
                    $model_user->save();
                }

                Session::set('user_uid', $user_uid);
            }
        }

        $user_uid = Session::get('user_uid');

        $this->modelUser = User::where('uid', $user_uid)->find();


        View::assign('user', $this->modelUser);
    }

    public function buildCloseAuthParam($params)
    {
        $pass_key = uniqid();

        $store_key = uniqid();

        Cache::set($store_key, [
            'pass_key' => $pass_key,
            'user_uid' => $this->modelUser->uid
        ]);

        return array_merge($params, [
            'store_key' => $store_key,
            'pass_key' => $pass_key
        ]);
    }

    public function verifyAuthRequire()
    {

        if ($this->disableLogin) {
            return false;
        }

        $user_uid = Session::get('user_uid');

        if (empty($user_uid)) {
            $store_key = $this->request->param('store_key');
            $pass_key = $this->request->param('pass_key');

            if (!empty($store_key) && !empty($pass_key)) {

                $user_session = Cache::pull($store_key);

                if ($user_session['pass_key'] == $pass_key) {

                    Session::set('user_uid', $user_session['user_uid']);

                    return false;
                }
            }
        } else {
            return false;
        }

        return true;
    }
}
